import axios from "./axios-instance"
import { fetchEventSource } from "@microsoft/fetch-event-source"

// export const getAiAnalysisApi = () => {
//   return axios.post("/ai/analyze-major")
// }
export const getAiAnalysisApi = (
  callback: (data: Record<string, any>, isDone: boolean) => void,
  ctrl: AbortController = new AbortController()
) => {
  fetchEventSource("/api/ai/analyze-major", {
    method: "POST",
    body: JSON.stringify({
      stream: true
    }),
    headers: {
      "Content-Type": "application/json",
      stream: "true"
    },
    signal: ctrl.signal,
    onmessage(event: Record<string, any>) {
      const data: Record<string, any> = JSON.parse(event.data)
      if (data.type === "DONE") {
        ctrl.abort()
      } else callback && callback(data, false)
    },
    onerror(error: Record<string, any>) {
      console.error("发生错误:", error)
    }
  })
}

// WebSocket连接
let ws: WebSocket | null = null
let messageCallback: ((data: Record<string, any>, isDone: boolean) => void) | null = null

// 初始化WebSocket连接
export const initWebSocket = () => {
  if (ws) return

  // 创建WebSocket连接
  ws = new WebSocket(`ws://${window.location.hostname}:3000`)

  // 连接建立时的处理
  ws.onopen = () => {
    console.log("WebSocket连接已建立")
  }

  // 接收消息的处理
  ws.onmessage = event => {
    try {
      const data = JSON.parse(event.data)

      // 根据消息类型处理
      switch (data.type) {
        case "status":
          // 处理状态消息
          console.log("状态:", data.content)
          break
        case "message":
          // 处理AI回复消息
          if (messageCallback) {
            messageCallback({ type: "message", content: data.content }, false)
          }
          break
        case "recommendations-schools":
          // 处理大学院校推荐
          if (messageCallback) {
            messageCallback({ type: "recommendations-schools", content: data.content }, false)
          }
          break
        case "recommendations-provinces":
          // 处理大学院校推荐省份
          if (messageCallback) {
            messageCallback({ type: "recommendations-provinces", content: data.content }, false)
          }
          break
        case "done":
          // 处理完成消息
          if (messageCallback) {
            messageCallback({ type: "done", content: data.content }, true)
          }
          break
        case "error":
          // 处理错误消息
          console.error("错误:", data.content)
          if (messageCallback) {
            messageCallback({ type: "error", content: data.content }, true)
          }
          break
      }
    } catch (error) {
      console.error("解析WebSocket消息时出错:", error)
    }
  }

  // 连接关闭时的处理
  ws.onclose = () => {
    console.log("WebSocket连接已关闭")
    ws = null
  }

  // 连接错误时的处理
  ws.onerror = error => {
    console.error("WebSocket连接错误:", error)
  }
}

// 发送消息到WebSocket服务器
export const sendWebSocketMessage = (messages: Record<string, any>[]) => {
  if (!ws || ws.readyState !== WebSocket.OPEN) {
    initWebSocket()

    // 等待连接建立
    setTimeout(() => {
      if (ws && ws.readyState === WebSocket.OPEN) {
        ws.send(
          JSON.stringify({
            type: "chat",
            messages: messages
          })
        )
      } else {
        console.error("WebSocket连接未建立，无法发送消息")
      }
    }, 1000)
  } else {
    ws.send(
      JSON.stringify({
        type: "chat",
        messages: messages
      })
    )
  }
}

// 使用WebSocket获取AI聊天回复
export const getAiChatApi = (
  messages: Record<string, any>[],
  callback: (data: Record<string, any>, isDone: boolean) => void
) => {
  // 保存回调函数
  messageCallback = callback

  // 发送消息到WebSocket服务器
  sendWebSocketMessage(messages)

  // 返回一个控制器，用于取消请求
  return {
    abort: () => {
      // 关闭WebSocket连接
      if (ws) {
        ws.close()
        ws = null
      }
      messageCallback = null
    }
  }
}

// 保留原有的HTTP接口，作为备用
export const getAiChatApiHttp = (
  messages: Record<string, any>[],
  callback: (data: Record<string, any>, isDone: boolean) => void
) => {
  const ctrl = new AbortController()
  fetchEventSource("/api/ai/chat-zhipu", {
    method: "POST",
    body: JSON.stringify({
      messages: messages
    }),
    headers: {
      "Content-Type": "application/json"
    },
    signal: ctrl.signal,
    onmessage(event: Record<string, any>) {
      const data: Record<string, any> = JSON.parse(event.data)
      if (data.type === "DONE") {
        ctrl.abort()
      } else callback && callback(data, false)
    }
  })

  return ctrl
}

// 专业智能分析
export const getMajorAnalysisApi = (params: Record<string, any>) => {
  return axios({
    method: "post",
    url: "/ai/major-analysis",
    data: {
      major: params.majorName,
      region: params.selectedRegion,
      city: params.selectedCity
    }
  })
}
